package com.sinosoft.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.sinosoft.gateway.config.Constants;
import com.sinosoft.gateway.model.RequestMessage;
import com.sinosoft.gateway.notice.NoticeQueue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;

@Component
@Slf4j
public class RequestFilter extends ZuulFilter {

    private static final String AUTHORIZATION = "auth";

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Autowired
    private NoticeQueue noticeQueue;

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI().toLowerCase();
        String domain = request.getScheme() + "://" + request.getServerName() + ":" + request.getLocalPort();
        try {
            if(ctx.get(Constants.IS_DEBUG_REQUEST_FLAG) != null){
                // record debug
                log.info("==============debug: {}", (RequestMessage) ctx.get("exec.requestBody"));
            }else{
                //获取header中透传的device-id
                String deviceId = request.getHeader("device_id");
                ctx.put("device_id", deviceId);

                Enumeration<String> header = request.getHeaderNames();
                Map<String, String> headerMap = new HashMap<>();
                while(header.hasMoreElements()){
                    String headerKey = header.nextElement();
                    String headVal = request.getHeader(headerKey);
                    headerMap.put(headerKey, headVal);
                }
                RequestMessage requestMessage = new RequestMessage();
                requestMessage.setHttpMethod(request.getMethod());
                requestMessage.setUrl(requestURI);
                requestMessage.setRequestBody(IOUtils.toString(request.getInputStream(), "utf-8"));
                requestMessage.setHeader(headerMap);
                CompletableFuture.runAsync(() -> {
                    noticeQueue.publish(requestMessage);
                    log.info("notice publish request:{}", JSON.toJSONString(requestMessage));
                });
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    private void setResponse(RequestContext ctx, boolean result, String responseBody){
        ctx.setSendZuulResponse(result);
        ctx.setResponseStatusCode(200);
        ctx.setResponseBody(responseBody);
        HttpServletResponse response = ctx.getResponse();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setLocale(new java.util.Locale("zh", "CN"));
    }

}